#include "mediachecker.h"
#include <Maestro/database.h>
MediaChecker::MediaChecker() {
    mediaObject=new Phonon::MediaObject(this);
    //connect(mediaObject,SIGNAL(metaDataChanged()),this,SLOT(metaDataChanged()));
    connect(mediaObject,SIGNAL(stateChanged(Phonon::State,Phonon::State)),this,SLOT(stateChanged(Phonon::State,Phonon::State)));
}

void MediaChecker::metaDataChanged() {
    qDebug() <<"data has changed "<<mediaObject->currentSource().fileName();
    qDebug() <<mediaObject->metaData();
}

void MediaChecker::stateChanged(Phonon::State newS, Phonon::State oldS) {
    //qDebug() << newS<<" "<<mediaObject->currentSource().fileName();
    if(!mediaObject->state()==Phonon::LoadingState) {
        //qDebug() <<"meta data is"<<mediaObject->metaData();
        if(mediaObject->metaData("ARTIST").size()>0) {
            file->artist=mediaObject->metaData("ARTIST").first();
        }
        if(mediaObject->metaData("TITLE").size()>0) {
            file->title=mediaObject->metaData("TITLE").first();
        }
        if(mediaObject->metaData("DESCRIPTION").size()>0) {
            file->description=mediaObject->metaData("DESCRIPTION").first();
        }
        mediaObject->metaData().clear();
        qDebug() <<mediaObject->currentSource().fileName();
        qDebug()<<"length of file "<<mediaObject->totalTime();
        Querier::updateMediaFile(file);
    }
    if(mediaObject->state()==Phonon::PlayingState||mediaObject->state()==Phonon::PausedState||mediaObject->state()==Phonon::StoppedState||mediaObject->state()==Phonon::ErrorState) {
        if(!queue.isEmpty()) {
            file=queue.first();
            queue.removeFirst();
            Phonon::MediaSource source(file->fileLocation+"/"+file->shortName);
            mediaObject->setCurrentSource(source);
        }
    }
}

bool MediaChecker::checkValid(MediaFile * file) {
    qDebug()<<mediaObject;
   // qDebug()<<(mediaObject->currentSource());
    qDebug()<<mediaObject->currentSource().type();
    if(mediaObject->currentSource().type()==Phonon::MediaSource::Empty) {
        Phonon::MediaSource source(file->fileLocation+"/"+file->shortName);
        if(source.type()!=source.Invalid&&source.type()!=source.Empty) {
            this->file=file;
            //qDebug()<<"source set, awaiting state change "<<source.fileName();
            //qDebug()<<source.type();
            mediaObject->setCurrentSource(source);
            mediaObject->play();
        } else {
            //qDebug() <<"file failed";
        }
    } else {
        queue.append(file);
    }

    return false;
}
